import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:get/get.dart';
import 'package:mziot/app/config/constant.dart';
import 'package:mziot/app/modules/devices/device_provider.dart';
import 'package:mziot/app/routes/app_pages.dart';
import 'package:mziot/app/tools/global_const.dart';
import 'package:mziot/app/tools/tools.dart';
import 'package:video_player/video_player.dart';

class InitController extends GetxController {
  //0-英文 1-中文 2-法语 3-德语
  final language = 999.obs;
  TextEditingController controller = TextEditingController();
  ScrollController scrollController = ScrollController();
  SwiperController swiperController = SwiperController();
  final dataList = <TimeZone>[].obs;
  final guideList = <dynamic>[].obs;
  VideoPlayerController? videoPlayerController;
  var isStart = false;
  final selectedIndex = 0.obs;

  @override
  void onInit() {
    super.onInit();
    dataList.value = Constant.timeZones;
  }

  @override
  void onReady() {
    super.onReady();
  }

  void setupTimeZone() {
    if (Get.arguments != null) {
      final zone = GlobalConst.userModel?.userTimeZone ?? '36';
      var offsetH = 0.0;
      var index = Constant.codeList.indexWhere((element) => element == int.parse(zone));
      if (index == -1) {
        index = Constant.codeList.indexWhere((element) => element == 36);
      }
      selectedIndex.value = index;
      offsetH = 59.0 * index;
      scrollController.animateTo(offsetH,
          duration: Duration(milliseconds: 300), curve: Curves.linear);
    } else {
      final zone = GlobalConst.sharedPreferences?.get(Constant.timeZone);
      var offsetH = 0.0;
      var index = Constant.timeZones.indexWhere((element) => element.zone == zone);
      if (index == -1) {
        index = Constant.timeZones.indexWhere((element) => element.zone == 'Africa/Monrovia');
      }
      selectedIndex.value = index;
      offsetH = 59.0 * index;
      scrollController.animateTo(offsetH,
          duration: Duration(milliseconds: 300), curve: Curves.linear);
    }
  }

  void setVideo() async {
    videoPlayerController = VideoPlayerController.asset('assets/start.mp4');
    await videoPlayerController?.initialize();
    videoPlayerController?.play();

    videoPlayerController?.addListener(() async {
      if (!videoPlayerController!.value.isPlaying &&
          videoPlayerController!.value.isInitialized &&
          !isStart) {
        isStart = true;
        GlobalConst.sharedPreferences?.setBool(Constant.kStart, false);
        await AppPages.INITIAL();
        // alertUpdate();
      }
    });
  }

  void fetchGuide({bool isPush = false}) {
    DeviceProvider.guideDance().then((value) async {
      if (value.isSuccess) {
        final guides = value.data ?? [];
        if (guides.isEmpty && !isPush) {
          GlobalConst.sharedPreferences?.setString(Constant.kInstall, 'value');
          AppPages.INITIAL();
          return;
        }
        guideList.value = guides;
        guides.forEach((element) {
          CachedNetworkImageProvider(element['img']);
        });
      }
    });
  }

  void fetchUpdateZone(String code) {
    EasyLoading.show();
    DeviceProvider.updateZone(code).then((value) async {
      if (value.isSuccess) {
        GlobalConst.userModel?.userTimeZone = code;
        GlobalConst.userModel?.isNeedSetTimezone = false;
        String info = json.encode(GlobalConst.userModel!.toJson());
        GlobalConst.sharedPreferences?.setString(Constant.kUser, info);
        if (Get.arguments != null) {
          Get.back();
        } else {
          AppPages.INITIAL();
        }
      } else {
        showToast(value.msg ?? '');
      }
    }).catchError((e) {
      showToast(e.toString());
    }).whenComplete(() => EasyLoading.dismiss());
  }

  void searchWords() {
    final text = controller.text.trim();
    var temp = Constant.timeZones;
    temp.retainWhere((element) => element.zone.toUpperCase().contains(text.toUpperCase()));
    dataList.value = temp;
  }

  @override
  void onClose() {}

  @override
  void dispose() async {
    await videoPlayerController?.dispose();
    controller.dispose();
    scrollController.dispose();
    swiperController.dispose();
    super.dispose();
  }
}
